package org.example.myleet.p861;

public class Solution {
    public int matrixScore(int[][] A) {
        //每个循环中，i是行，j是列
        //每一行第一个位置翻转成1
        for (int i=0; i<A.length; i++) {
            if (A[i][0] < 1) {
                flipRow(A, i);
            }
        }
        //从第二列开始，每一列都翻转成1最多的情况
        for (int j=1; j<A[0].length; j++) {
            int oneCount = 0, zeroCount = 0;
            for (int i=0; i<A.length; i++) {
                if (A[i][j] < 1) {
                    ++zeroCount;
                } else {
                    ++oneCount;
                }
            }
            if (oneCount < zeroCount) {
                flipCol(A, j);
            }
        }
        //计算结果
        int sum = 0;
        for (int i=0; i<A.length; i++) {
            int row = 0;
            for (int j=0; j<A[i].length; j++) {
                row += A[i][j] << (A[i].length - 1 - j);
            }
            sum += row;
        }
        return sum;
    }

    private void flipRow(int[][] A, int row) {
        for (int i=0; i<A[0].length; i++) {
            A[row][i] = A[row][i] ^ 1;
        }
    }

    private void flipCol(int[][] A, int col) {
        for (int i=0; i<A.length; i++) {
            A[i][col] = A[i][col] ^ 1;
        }
    }
}
